<?php

function verifyIdCard($idCard) {
    $flag = false;
    $regIdCard = '/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/';

    if (preg_match($regIdCard, $idCard)) {
        if (strlen($idCard) == 18) {
            $idCardWi = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
            $idCardY = array(1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2);
            $idCardWiSum = 0;

            for ($i = 0; $i < 17; $i++) {
                $idCardWiSum += intval(substr($idCard, $i, 1)) * $idCardWi[$i];
            }

            $idCardMod = $idCardWiSum % 11;
            $idCardLast = strtoupper(substr($idCard, 17));

            if ($idCardMod == 2) {
                if ($idCardLast == 'X') {
                    $flag = true;
                } else {
                    echo json_encode(array('code' => -2, 'msg' => '身份证最后一位输入错误'));
                    exit;
                }
            } else {
                if ($idCardLast == $idCardY[$idCardMod]) {
                    $flag = true;
                } else {
                    echo json_encode(array('code' => -2, 'msg' => '身份证信息不正确'));
                    exit;
                }
            }
        } else if (strlen($idCard) == 15) {
            $id17 = substr($idCard, 0, 6) . '19' . substr($idCard, 6);
            $parityBit = getParityBit($id17);
            $tempIdCard = $id17 . $parityBit;
            $flag = validateIdCard($tempIdCard);
        }
    } else {
        echo json_encode(array('code' => -2, 'msg' => '身份证号码有误，请重新输入'));
        exit;
    }

    return $flag;
}